package com.ruoyi.merchant.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.merchant.domain.MessageSession;
import com.ruoyi.merchant.domain.MessageStatistics;
import com.ruoyi.merchant.domain.NotificationSettings;
import com.ruoyi.merchant.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 商家端消息中心控制器
 */
@RestController
@RequestMapping("/merchant/messages")
public class MerchantMessageController extends BaseController {

    @Autowired
    private IMessageService messageService;

    /**
     * 获取消息统计数据
     */
    @GetMapping("/statistics")
    public AjaxResult getMessageStatistics() {
        Long merchantId = getMerchantId();
        MessageStatistics statistics = messageService.getMessageStatistics(merchantId);
        return AjaxResult.success(statistics);
    }

    /**
     * 获取消息会话列表
     */
    @GetMapping("/sessions")
    public TableDataInfo getMessageSessions(@RequestParam(value = "msgType", required = false) String msgType,
                                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Long merchantId = getMerchantId();
        startPage();
        List<MessageSession> sessions = messageService.getMessageSessions(merchantId, msgType, pageNum, pageSize);
        return getDataTable(sessions);
    }

    /**
     * 获取会话聊天记录
     */
    @GetMapping("/sessions/{sessionId}/history")
    public TableDataInfo getChatHistory(@PathVariable Long sessionId,
                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        Long merchantId = getMerchantId();
        startPage();
        List<Map<String, Object>> records = messageService.getChatHistory(sessionId, merchantId, pageNum, pageSize);
        return getDataTable(records);
    }

    @PostMapping("/sessions/{sessionId}/send")
    public AjaxResult sendMessage(@PathVariable Long sessionId,
                                  @RequestBody Map<String, Object> params) {
        // 从 token 获取商家ID
        Long merchantIdFromToken = getMerchantId();

        // 从请求参数获取商家ID
        Long merchantIdFromRequest = null;
        if (params.get("merchantId") != null) {
            merchantIdFromRequest = ((Number) params.get("merchantId")).longValue();
        }

        // 优先使用请求中的 merchantId，否则使用 token 中的
        Long merchantId = merchantIdFromRequest != null ? merchantIdFromRequest : merchantIdFromToken;

        String content = (String) params.get("content");
        String messageType = (String) params.get("messageType");
        Map<String, Object> attachments = (Map<String, Object>) params.get("attachments");

        // 获取 customerId
        Long customerId = null;
        if (params.get("customerId") != null) {
            customerId = ((Number) params.get("customerId")).longValue();
        }

        if (content == null || content.trim().isEmpty()) {
            return AjaxResult.error("消息内容不能为空");
        }
        if (content.length() > 1000) {
            return AjaxResult.error("消息内容不能超过1000个字符");
        }
        if (messageType == null) {
            messageType = "text";
        }

        // 添加调试日志
        System.out.println("DEBUG - Controller merchantIdFromToken: " + merchantIdFromToken);
        System.out.println("DEBUG - Controller merchantIdFromRequest: " + merchantIdFromRequest);
        System.out.println("DEBUG - Controller final merchantId: " + merchantId);
        System.out.println("DEBUG - Controller customerId: " + customerId);
        System.out.println("DEBUG - Controller messageType: " + messageType);
        System.out.println("DEBUG - Controller attachments: " + attachments);

        int result = messageService.sendMessage(sessionId, merchantId, customerId, content, messageType, attachments);
        return result > 0 ? AjaxResult.success("发送成功") : AjaxResult.error("发送失败");
    }

    /**
     * 发送优惠券
     */
    @PostMapping("/sessions/{sessionId}/send-coupon")
    public AjaxResult sendCoupon(@PathVariable Long sessionId,
                                 @RequestBody Map<String, Object> params) {
        Long merchantId = getMerchantId();
        Long couponTemplateId = Long.valueOf(params.get("couponTemplateId").toString());
        String customMessage = (String) params.get("customMessage");

        // 获取 customerId
        Long customerId = null;
        if (params.get("customerId") != null) {
            customerId = ((Number) params.get("customerId")).longValue();
        }

        if (customMessage != null && customMessage.length() > 200) {
            return AjaxResult.error("自定义消息不能超过200个字符");
        }

        int result = messageService.sendCoupon(sessionId, merchantId, customerId, couponTemplateId, customMessage);
        return result > 0 ? AjaxResult.success("发送成功") : AjaxResult.error("发送失败");
    }

    /**
     * 标记消息已读
     */
    @PutMapping("/sessions/{sessionId}/mark-read")
    public AjaxResult markMessagesAsRead(@PathVariable Long sessionId,
                                         @RequestBody(required = false) Map<String, List<Long>> params) {
        Long merchantId = getMerchantId();
        List<Long> messageIds = params != null ? params.get("messageIds") : null;

        try {
            int result = messageService.markMessagesAsRead(sessionId, merchantId, messageIds);
            if (result >= 0) {
                return AjaxResult.success("操作成功");
            } else {
                return AjaxResult.error("操作失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 获取可用优惠券列表
     */
    @GetMapping("/available-coupons")
    public AjaxResult getAvailableCoupons() {
        Long merchantId = getMerchantId();
        List<Map<String, Object>> coupons = messageService.getAvailableCoupons(merchantId);
        return AjaxResult.success(coupons);
    }

    /**
     * 删除消息会话
     */
    @DeleteMapping("/sessions/{sessionId}")
    public AjaxResult deleteMessageSession(@PathVariable Long sessionId) {
        Long merchantId = getMerchantId();
        int result = messageService.deleteMessageSession(sessionId, merchantId);
        return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    /**
     * 获取消息通知设置
     */
    @GetMapping("/notification-settings")
    public AjaxResult getNotificationSettings() {
        Long merchantId = getMerchantId();
        NotificationSettings settings = messageService.getNotificationSettings(merchantId);
        return AjaxResult.success(settings);
    }

    /**
     * 更新消息通知设置
     */
    @PutMapping("/notification-settings")
    public AjaxResult updateNotificationSettings(@RequestBody NotificationSettings settings) {
        Long merchantId = getMerchantId();
        int result = messageService.updateNotificationSettings(merchantId, settings);
        return result > 0 ? AjaxResult.success("更新成功") : AjaxResult.error("更新失败");
    }

    /**
     * 从Token中获取商家ID
     *
     */
    private Long getMerchantId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return loginUser.getUserId();
    }

    /**
     * 获取用户最新订单详情
     */
    @GetMapping("/sessions/{sessionId}/latest-order")
    public AjaxResult getLatestOrderBySession(@PathVariable Long sessionId) {
        Long merchantId = getMerchantId();
        try {
            Map<String, Object> order = messageService.getLatestOrderBySessionId(sessionId, merchantId);
            return AjaxResult.success(order);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}